<template>
  <MyModal ref="myModal" title="修改余额" :top="35" :width="550">
    <template #content>
      <a-form
        ref="formRef"
        :rules="rules"
        :model="formState"
        :label-col="labelCol"
        style="padding-left: 60px"
      >
        <a-form-item has-feedback label="昵称" name="nickName">
          <a-input v-model:value="formState.nickName" disabled></a-input>
        </a-form-item>

        <a-form-item has-feedback label="微信号" name="account">
          <a-input v-model:value="formState.account" disabled></a-input>
        </a-form-item>

        <a-form-item has-feedback label="类型" name="type">
          <a-select v-model:value="formState.type" placeholder="请选择" style="width: 70%">
            <a-select-option v-for="(item, index) in typeList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item has-feedback label="金额" name="changeBalance">
          <a-input-number
            v-model:value="formState.changeBalance"
            style="width: 70%"
          ></a-input-number>
        </a-form-item>

        <a-form-item style="padding-left: 44%">
          <a-button style="margin-right: 10px" @click="myModal.cancelModal()">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </a-form-item>
      </a-form>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { toYuan, regYuanToFen } from '@/hooks/util'
import * as fansApi from '@/api/fans'
import { message } from 'ant-design-vue'

const myModal = ref()

import type { SelectProps } from 'ant-design-vue'
const typeList = ref<SelectProps['options']>([
  {
    label: '加钱',
    value: '1',
  },
  {
    label: '减钱',
    value: '2',
  },
])

const rowInfo = ref<any>({})
const showModal = (record: any) => {
  rowInfo.value = record
  formState.value.nickName = record.nickName
  formState.value.account = record.account
  // formState.value.changeBalance = toYuan(record.balance) as any

  myModal.value?.showModal()
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

const formRef = ref()
let labelCol = { span: 4 }
interface formState {
  nickName: string
  account: string
  type: string
  changeBalance: number
}
const formState = ref<formState>({
  nickName: '',
  account: '',
  type: '1',
  changeBalance: 0,
})

import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateChangeBalance = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }

  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }

  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }

  // 如果一切正常，返回成功
  return Promise.resolve()
}
import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  changeBalance: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
}

// 登录
const handleSubmit = async () => {
  formRef.value.validate().then(async () => {
    // console.log('formState=', formState.value)
    let params = {
      changeBalance: regYuanToFen(formState.value.changeBalance, 100),
      fansId: rowInfo.value.id,
      type: formState.value.type,
    }
    // console.log('params=', params)
    try {
      const { state, message: msg } = await fansApi.editWechatFansBalance(params)
      if (state === 200) {
        myModal.value?.cancelModal()
        emit('refresh')
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  })
}
</script>

<style scoped lang="less">
input {
  width: 70%;
}
</style>
